package com.taokatao.cardmee;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.view.WindowCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.common.CropImageActivity;
import com.taokatao.cardmee.common.widget.AlertDialog;
import com.taokatao.cardmee.common.widget.TouchBackLayout;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageOptions;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;
import butterknife.Optional;
import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;


public class BaseActivity extends AppCompatActivity {
    private static final String IMAGE_FROM_CONTENT = "content";
    private static final String IMAGE_FROM_FILE = "file";
    protected static final int REQUEST_CODE_CAPTURE_PICTURE = 412;
    protected static final int REQUEST_CODE_PICK_IMAGE = 413;
    protected static final int REQUEST_CODE_CROP_IMAGE = 414;
    public static final int REQUEST_CODE_SCAN_CODE = 415;

    protected String picTag;
    protected int cropAspectX = 1;
    protected int cropAspectY = 1;
    protected int expectedOutputCropWidth = 0;
    protected int expectedOutputCropHeight = 0;
    protected TouchBackLayout layTouchToBack;
    protected boolean isSupportTouchBack = true;
    protected boolean isLandscapeMode = false;
    private boolean isTransparentBackgroundColor = false;
    private boolean isTranslucentStatus = true;
    public boolean isAppDefaultTransitions = true;

    private File fCapturePicture;
    protected boolean isCropImageMode = true;
    protected static final int CODE_FOR_CAMERA_PERMISSION = 102;
    protected static final int CODE_FOR_PHOTO_PERMISSION = 103;
    protected static final int CODE_FOR_LOCATION_PERMISSION = 104;

    private final List<SubscriberAdapter> mRequestCallbacks = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (isTransparentBackgroundColor) {
            getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isTranslucentStatus) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }


        supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_MODE_OVERLAY);

        setRequestedOrientation(isLandscapeMode ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
        Utils.logd("EventBus onCreate register %s", getClass().getSimpleName());
        ActivityCollector.addActivity(this);

    }

    public SubscriberAdapter registerSubscriberAdapter(SubscriberAdapter adapter) {
        if (!mRequestCallbacks.contains(adapter)) {
            mRequestCallbacks.add(adapter);
        }

        return adapter;
    }

    @Optional
    @OnClick(R.id.l_container)
    void hideSoftInput() {
        Utils.hideSoftInputFromWindowAlways(this);
        onHideSoftInput();
    }

    protected void onHideSoftInput() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        for (SubscriberAdapter subscriberAdapter : mRequestCallbacks) {
            subscriberAdapter.unsubscribe();
        }

        EventBus.getDefault().unregister(this);
        Utils.logd("EventBus onDestroy unregister %s", getClass().getSimpleName());
        ActivityCollector.removeActivity(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        JPushInterface.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        JPushInterface.onResume(this);
    }

    public void openCamera(int aspectX, int aspectY, int expectedWidth, int expectedHeight, String tag) {
        cropAspectX = aspectX;
        cropAspectY = aspectY;
        expectedOutputCropWidth = expectedWidth;
        expectedOutputCropHeight = expectedHeight;
        picTag = tag;
        openCamera();
    }

    public void openCamera() {
        if (!AndPermission.hasPermission(this, Manifest.permission.CAMERA)) {
            AndPermission.with(this)
                    .requestCode(CODE_FOR_CAMERA_PERMISSION)
                    .permission(Manifest.permission.CAMERA)
                    .send();
            return;
        }

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fCapturePicture = new File(getExternalCacheDir(), "pic_" + System.currentTimeMillis() + ".jpg");
        try {
            if (!fCapturePicture.exists()) {
                fCapturePicture.createNewFile();
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(fCapturePicture));
            startActivityForResult(intent, REQUEST_CODE_CAPTURE_PICTURE);
        } catch (IOException e) {
            e.printStackTrace();
            Utils.showToast("图片无法保存");
        }
    }

    public void openPhotos(int aspectX, int aspectY, int expectedWidth, int expectedHeight, String tag) {
        cropAspectX = aspectX;
        cropAspectY = aspectY;
        expectedOutputCropWidth = expectedWidth;
        expectedOutputCropHeight = expectedHeight;
        picTag = tag;
        openPhotos();
    }

    public void openPhotos() {
        if (!AndPermission.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            AndPermission.with(this)
                    .requestCode(CODE_FOR_PHOTO_PERMISSION)
                    .permission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    .send();
            return;
        }

        Intent intentPick = new Intent(Intent.ACTION_PICK);
        intentPick.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        try {
            startActivityForResult(intentPick, REQUEST_CODE_PICK_IMAGE);
        } catch (ActivityNotFoundException e) {
            Intent intentGetContent = new Intent(Intent.ACTION_GET_CONTENT);
            intentGetContent.setType("image/*");
            Intent wrapperIntent = Intent.createChooser(intentGetContent, null);
            try {
                startActivityForResult(wrapperIntent, REQUEST_CODE_PICK_IMAGE);
            } catch (ActivityNotFoundException e1) {
                Utils.showToast("没有找到文件浏览器或相册");
            }
        }
    }

    public void cropImage(Uri data) {
        if (!isCropImageMode) {
            Utils.logd("openCamera crop_image : %s %n", fCapturePicture.getAbsolutePath());
            onPictureQueryOut(fCapturePicture.getAbsolutePath());
            return;
        }

        fCapturePicture = new File(getExternalCacheDir(), "pic_crop_" + System.currentTimeMillis() + ".jpg");
//        CropImage.ActivityBuilder builder = CropImage.activity(data)
//                .setFixAspectRatio(true)
//                .setAspectRatio(cropAspectX, cropAspectY)
//                .setGuidelines(CropImageView.Guidelines.OFF)
//                .setActivityTitle("裁剪");
//        if (expectedOutputCropWidth > 0 && expectedOutputCropHeight > 0) {
//            builder.setRequestedSize(expectedOutputCropWidth, expectedOutputCropHeight);
//            builder.setOutputCompressQuality(70);
//        }
//        builder.start(this);
        Intent intent = new Intent(this, CropImageActivity.class);
        CropImageOptions options = new CropImageOptions();
        options.aspectRatioX = cropAspectX;
        options.aspectRatioY = cropAspectY;
        options.guidelines = CropImageView.Guidelines.OFF;
        options.fixAspectRatio = true;
        intent.putExtra(CropImage.CROP_IMAGE_EXTRA_OPTIONS, options);
        intent.putExtra("extra_output_uri", Uri.fromFile(fCapturePicture));
        intent.putExtra("extra_data_uri", data);
        intent.putExtra("extra_output_width", expectedOutputCropWidth);
        intent.putExtra("extra_output_height", expectedOutputCropHeight);
        startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Utils.logd(getClass().getSimpleName() + " onActivityResult requestCode:" + requestCode + "#resultCode:" + resultCode + "#data:" + data);

        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            if (resultCode == RESULT_OK) {
                Uri imageUri = data.getData();
                if (imageUri != null && IMAGE_FROM_FILE.equals(imageUri.getScheme())) {
                    Utils.logd("openPhotos pick_image %s %n", imageUri.getPath());
                    cropImage(Uri.fromFile(new File(imageUri.getPath())));
                } else if (imageUri != null && IMAGE_FROM_CONTENT.equals(imageUri.getScheme())) {
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
                    if (cursor != null) {
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String picturePath = cursor.getString(columnIndex);
                        cursor.close();
                        Utils.logd("openPhotos pick_image %s %n", picturePath);
                        cropImage(Uri.fromFile(new File(picturePath)));
                    } else {
                        Utils.loge("openPhotos pick_image cursor null");
                    }
                } else {
                    Utils.showToast("图片获取失败");
                    Utils.loge(imageUri != null ? ("openPhotos unknown uri\n" + imageUri.getPath()) : "openPhotos imageUri null");
                }
            }
        } else if (requestCode == REQUEST_CODE_CAPTURE_PICTURE) {
            if (resultCode == RESULT_OK) {
                Utils.logd("openCamera %s %n", fCapturePicture.getAbsolutePath());
                cropImage(Uri.fromFile(fCapturePicture));
            }
        } else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                fCapturePicture = new File(CropImage.getActivityResult(data).getUri().getPath());
                onPictureQueryOut(fCapturePicture.getAbsolutePath());
            } else {
                Utils.showToast("图片裁剪失败");
            }
        } else if (requestCode == REQUEST_CODE_CROP_IMAGE) {
            if (resultCode == RESULT_OK) {
                Uri output = data.getParcelableExtra("extra_output_uri");
                fCapturePicture = new File(output.getPath());
                onPictureQueryOut(fCapturePicture.getAbsolutePath());
            } else {
                Utils.showToast("图片裁剪失败");
            }
        }

        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    // 当定位权限打开啦
    protected void onLocationPermissionAllowed() {
        Utils.logd("%s onLocationPermissionAllowed: ", getClass().getSimpleName());
    }

    protected void onPhotoPermissionAllowed() {
        Utils.logd("%s onPhotoPermissionAllowed: ", getClass().getSimpleName());
    }

    protected void onCameraPermissionAllowed() {
        Utils.logd("%s onCameraPermissionAllowed: ", getClass().getSimpleName());
    }

    // 当图片选择出来啦
    protected void onPictureQueryOut(String path) {
        Utils.logd("%s onPictureQueryOut: %s", getClass().getSimpleName(), path);
    }

    public void onEventMainThread(BusEvent event) {
        if (event.type == BusEvent.TYPE_MAIN_THREAD) {
            Utils.logd("%s onEventMainThread: action[%d]", getClass().getSimpleName(), event.action);
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (fCapturePicture != null)
            Utils.spWrite(C.settings.CAPTURE_PICTURE, fCapturePicture.getAbsolutePath());
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        String picturePath = Utils.spReadString(C.settings.CAPTURE_PICTURE);
        if (!TextUtils.isEmpty(picturePath)) fCapturePicture = new File(picturePath);
        Utils.spWrite(C.settings.CAPTURE_PICTURE, "");
    }


    @Override
    public void setContentView(int layoutResID) {
        setContentView(LayoutInflater.from(this).inflate(layoutResID, null));
    }

    @Override
    public void setContentView(View view) {
        setContentView(view, null);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        View viewContainer;
        if (isSupportTouchBack) {
            layTouchToBack = new TouchBackLayout(this);
            layTouchToBack.setOnTouchCallback(new TouchBackLayout.Callback() {
                @Override
                public void onTouchBack(View view) {
                    if (ActivityCollector.size() > 1) {
                        finish();
                    }
                }
            });
            layTouchToBack.addView(view);
            viewContainer = layTouchToBack;
        } else {
            viewContainer = view;
        }

        if (params != null) {
            super.setContentView(viewContainer, params);
        } else {
            super.setContentView(viewContainer);
        }
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        if (isAppDefaultTransitions) {
            overridePendingTransition(R.anim.slide_right_enter, R.anim.slide_left_exit);
        }

    }

    @Override
    public void finish() {
        Utils.hideSoftInputFromWindowAlways(this);
        super.finish();
        if (isAppDefaultTransitions && ActivityCollector.size() > 1) {
            overridePendingTransition(R.anim.slide_left_enter, R.anim.slide_right_exit);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Utils.logd("onRequestPermissionsResult requestCode:" + requestCode);
        for (int i = 0; i < permissions.length; i++) {
            String result = grantResults.length > i ? String.valueOf(grantResults[i]) : "unknown";
            Utils.logd("onRequestPermissionsResult permissions[]:%s#grantResults[]:%s", permissions[i], result);
        }
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // Toast.makeText(getApplicationContext(), "onSucceed " + requestCode + "##", Toast.LENGTH_SHORT).show();
            // 权限申请成功回调。
            if (CODE_FOR_CAMERA_PERMISSION == requestCode) {
                onCameraPermissionAllowed();
            } else if (CODE_FOR_PHOTO_PERMISSION == requestCode) {
                onPhotoPermissionAllowed();
            } else if (CODE_FOR_LOCATION_PERMISSION == requestCode) {
                onLocationPermissionAllowed();
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            // Toast.makeText(getApplicationContext(), "onFailed " + requestCode + "##", Toast.LENGTH_SHORT).show();
            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(BaseActivity.this, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(BaseActivity.this, requestCode).show();
            } else {
                String message = "";
                if (CODE_FOR_CAMERA_PERMISSION == requestCode) {
                    message = "您好，卡蜜需要获得相机权限才能打开您手机的摄像头来完成一些需要图片拍摄，对条形码、二维码的识别扫描等相关功能。";
                } else if (CODE_FOR_PHOTO_PERMISSION == requestCode) {
                    message = "您好，卡蜜需要获得SD卡文件读写权限才能使用、展示一些手机图片文件等资源。";
                } else if (CODE_FOR_LOCATION_PERMISSION == requestCode) {
                    message = "您好，卡蜜需要获得定位权限才能获得您的当前坐标来进行距离推算，附近查找，推荐等相关功能。";
                }
                if (!TextUtils.isEmpty(message)) {
                    new AlertDialog.Builder(BaseActivity.this).setTitle("权限提示")
                            .setMessage(message)
                            .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).setCancelable(false).create().show();
                }
            }
        }
    };

}
